﻿using System;
#if NET451
using System.Configuration;
#endif
#if NETSTANDARD2_0
using Microsoft.Extensions.Configuration;
using System.IO;
#endif

namespace RabbitMQExtension
{
    public class MQFactory
    {
        public static IMQConsumerClient GetMQConsumer()
        {
            var config = GetDefaultConfig(true);
            return GetMQConsumer(config);
        }

        public static IMQConsumerClient GetMQConsumer(MQConfig config)
        {
            var consumer = new MQConsumerClient();
            consumer.SetConnectInfo(config);
            return consumer;
        }
        public static IMQProducerClient GetMQProducer()
        {
            var config = GetDefaultConfig();
            return GetMQProducer(config);
        }
        public static IMQProducerClient GetMQProducer(MQConfig config)
        {
            var producer = new MQProducerClient();
            producer.SetConnectInfo(config);
            return producer;
        }

        public static MQConfig GetDefaultConfig(bool isConsumer = false)
        {
#if NET451
            var maxThread = 4;
            if (isConsumer)
            {
                var maxThreadStr = ConfigurationManager.AppSettings["MQ.MaxComsumerThreads"];
                if (!string.IsNullOrEmpty(maxThreadStr))
                {
                    if (int.TryParse(maxThreadStr.Trim(), out var thread))
                    {
                        if (thread > 0)
                            maxThread = thread;
                    }
                }
            }
            MQConfig config = new MQConfig(ConfigurationManager.AppSettings["MQ.Host"], ConfigurationManager.AppSettings["MQ.UserName"], ConfigurationManager.AppSettings["MQ.Password"], ConfigurationManager.AppSettings["MQ.VirtualHost"], maxThread);
#endif
#if NETSTANDARD2_0
            MQConfig config = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json", true, true).Build().GetSection("MQ").Get<MQConfig>();
#endif
            if (string.IsNullOrEmpty(config.Host))
                throw new ArgumentNullException("Host");
            if (string.IsNullOrEmpty(config.UserName))
                throw new ArgumentNullException("UserName");
            if (string.IsNullOrEmpty(config.Password))
                throw new ArgumentNullException("Password");

            return config;
        }
    }
}
